<?php
/*
 *具体比赛的控制管理
 *具体比赛属于比赛下的一项, 作为比赛的下一层级进行管理
 *@author susy.liang<liangling@ilngyuan.com.cn>
 */

namespace Admin\Controller;

class RaceController extends BaseManageController {

	/**
	 *比赛的模型对象名
	 *@var string
	 *@access protected
	 */
	protected $modelName = 'Admin/Video';

	/**
	 *删除类型
	 *@var bool false|逻辑删除 true|物理删除
	 *@access protected
	 */
	protected $is_del = false;

	/**
	 *模型项的相应值的文本描述
	 *@var array
	 *@access protected
	 */
	protected $text_map = array(
		'status' => array(0 => '禁用', '1' => '开启', '-1' => '删除'),
		'match_state' => array(0 => '普通', 1 => '预告', 2 => '直播中'),
	);

	public function _before_index() {
		$this->setGroup();

		$searchMap = array();
		$this->title = $title = I('title');
		if ($title) {
			$searchMap['title'] = array('like', (string) $title);
		}

		$this->date = $date = I('date');
		if ($date) {
			$searchMap['match_time'] = strtotime($date);
		}

		$searchMap['group_id'] = $this->groupId;

		$this->where = $searchMap;

	}

	protected function setGroup() {
		if (!I('group_id')) {
			$this->error('参数错误');
		}
		$this->groupId = I('group_id', 0, 'intval');
		$this->group = A('Api/RaceGroup', 'Event')->info($this->groupId);

		if (!$this->group) {
			$this->error('赛程信息错误');
		}

	}

	protected function setIcons() {
		$this->iconsOptions = A('Api/IconPacks', 'Event')->getIcons(2);
	}

	protected function setTeam() {
		$match = A('Api/Match', 'Event')->info(intval($this->group['match_id']));
		$teamMap = array(
			'game_id' => $match['game_id'],
			'status' => array('gt', 0),
		);
		$this->teams = D('Common/Team', 'Service')->where($teamMap)->field('id,name')->select();
	}

	protected function setMatch() {
		$this->match = A('Api/Match', 'Event')->info($this->group['match_id']);
	}

	/**
	 *添加比赛
	 */
	public function add() {
		if (IS_POST) {

			$vService = D('Admin/Video', 'Service');

			$data = I('');
			$data['type'] = $vService::TYPE_MATCH;
			$data['status'] = $vService::STATUS_PEDDING;
			$data['uid'] = UID;

			$data = $vService->create($data);
			if ($data && $vService->add($data)) {
				$this->success('操作成功');
			} else {
				$this->error($vService->getError());
			}

		} else {

			$this->setGroup();
			if (!$this->group['competitor']) {
				$this->error('请先完善【' . $this->group['title'] . '】战队信息');
			}

			$this->setIcons();
			$this->setMatch();

			$this->display('form');
		}
	}

	/**
	 *编辑比赛
	 *@susy<susy.liang@ilongyuan.com.cn>
	 */
	public function edit($id) {

		$id = intval($id);

		$vService = D('Admin/Video', 'Service');
		$data = $vService->find($id);
		if (empty($data)) {
			$this->error('非法操作项');
		}

		if (IS_POST) {

			$update = I('');
			$update['id'] = $id;

			unset($update['match_id']);
			unset($update['game_id']);
			if (!$update['icons']) {
				$update['icons'] = array();
			} else {
				$update['icons'] = array_map('intval', $update['icons']);
			}

			// 第三方推荐标识 liubo 2016-07-12
			if (!$update['third_tags']) {
				$update['third_tags'] = [];
			}

			$update = $vService->create($update);
			if ($update && $vService->where(array('id' => $id))->save($update)) {
				//$this->addJoiner($data);
				$this->success('更新成功');

			} else {
				$this->error($vService->getError());
			}

		} else {

			$this->data = $data;
			$this->id = $id;

			$this->setGroup();
			$this->setIcons();
			$this->setMatch();

			$this->display('form');

		}
	}

	/**
	 *设置比赛的视频
	 *@param int $id 比赛标识
	 *@author susy<susy.liang@ilongyuan.com.cn>
	 */

	// 重构比赛视频的视频组成和逻辑 2015-6-15 19:33:33 Legend.
	public function video($id, $groupId) {

		$id = intval($id);
		$servObj = D('Video', 'Service');

		if (IS_POST) {

			// $data = I('');
			/*if(empty($data['time_group']) || empty($data['videos']))
				$this->error('请设置时间组或视频');*/

			/*$update['videos']    = $data['videos'];
			$update['time_group'] =  trim($data['time_group'], ",;\r\n");*/
			$delete = I('delete');
			$time_groups = I('video_times');
			foreach ($time_groups as $video_id => $time) {
				if (!in_array($video_id, $delete)) {
					$videos[$time] = intval($video_id);
				}
			}
			ksort($videos);
			$update['match_videos'] = array();
			$update['match_times'] = array();
			foreach ($videos as $time => $video) {
				$update['match_videos'][] = $video;
				$update['match_times'][] = $time;
			}

			$flg = $servObj->where(array('id' => $id))->save($update);
			if ($flg) {
				$this->success('操作成功');
			} else {
				$this->error('操作失败，请联系管理员');
			}

		} else {

			$race = $servObj->field('title,match_videos,match_times')->find($id);
			$match_videos = $race['match_videos'] ? array_map('intval', $race['match_videos']) : array();

			$map = array(
				'id' => array('in', $match_videos),
				'status' => array('egt', 0),
			);
			$videos = $servObj->where($map)->field('id,full_title,title,detail,play')->select();
			foreach ($videos as $key => $value) {
				$temp[$value['id']] = $value;
			}
			$this->videos = $temp;
			$this->race = $race;
			$this->videos_times = array_keys($race['videos']);
			$this->id = $id;
			$this->groupId = $groupId;
			$this->display('video');

		}
	}

	public function sync() {
		// 调整数据结构脚本

	}

	/**
	 * 删除比赛下的视频
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */

	public function delVideo() {
		$race_id = I('request.race_id', 0, 'intval');
		$id = array_unique((array) I('id', 0));
		$id = is_array($id) ? array_map('intval', $id) : intval($id);
		$servObj = D('Video', 'Service');
		$race = $servObj->field('id,match_videos,match_times')->find($race_id);

		if (!$race) {
			$this->error('比赛信息错误!');
		}

		if (!$id) {
			$this->error('需选择删除的项目!');
		}
		$map['id'] = array('in', $id);
		//删除不能直接调用父类的方法 susy.liang<liangling@ilongyuan.com.cn> at 2015/8/10
		/*if ($servObj->is_del)
		{
			$res = $servObj->model->where($map)->delete();
		}
		else
		{
			$res = $this->delete('Common/Video', $map );
		}*/
		if ($servObj->is_del) {
			$res = $servObj->model->where($map)->delete();
		} else {

			$update = array(
				'status' => $servObj::STATUS_DEL,
				'update_time' => NOW_TIME,
			);
			$res = $servObj->where($map)->save($update);

		}
		//end
		if ($res) {
			//更新比赛的视频组信息的修改 by susy.liang at 2015/8/10
			/*$match_videos = array_map('intval', array_diff($race['match_videos'], $id) );
			$servObj->where(array('id' => $race_id))->setField('match_videos', $match_videos);*/
			$this->updateRaceVideo($race, $id);
			//end
			$this->success('操作成功');
		} else {
			$this->error('操作失败');
		}

	}

	/**
	 *更新比赛的视频对象
	 *@author susy.liang<liangling@ilongyuan.com.cn>
	 */
	private function updateRaceVideo($raceData = array(), $rmIds = array()) {

		$videosArr = array();
		$timesArr = array();
		$servObj = D('Video', 'Service');

		foreach ($raceData['match_videos'] as $key => $value) {
			if (!in_array($value, $rmIds)) {
				$videosArr[] = $value;
				$timesArr[] = $raceData['match_times'][$key];
			}
		}
		$update = array(
			'match_videos' => array_map('intval', $videosArr),
			'match_times' => $timesArr,
		);
		$servObj->where(array('id' => intval($raceData['id'])))->save($update);

		return;
	}

	/**
	 *比赛视频的移除
	 *视频将变为普通的视频
	 *@author susy.liang<liangling@ilongyuan.com.cn>
	 */
	public function rmVideo() {

		$raceId = I('request.race_id', 0, 'intval');
		$id = array_unique((array) I('id', 0));
		$id = is_array($id) ? array_map('intval', $id) : intval($id);

		if (!$id) {
			$this->error('需选择删除的项目!');
		}

		$servObj = D('Video', 'Service');
		$race = $servObj->field('id,match_videos,match_times')->find($raceId);
		if (!$race) {
			$this->error('比赛信息错误!');
		}

		$map = array('id' => array('in', $id));

		$update = array(
			'update_time' => NOW_TIME,
			'race_id' => null,
		);
		$res = $servObj->where($map)->save($update);
		if ($res) {
			$this->updateRaceVideo($race, $id);
			$this->success('移除成功');
		} else {
			$this->error('移除失败');
		}
	}

	/**
	 *比赛视频的推荐
	 *用于前台比赛列表的展示 最多推3个
	 *video_id|视频id group_id|比赛组id  id|比赛id
	 *@author susy.liang<liangling@ilongyuan.com.cn>
	 */
	public function setRecommend() {
		$param = array_map('intval', I(''));
		$videoId = $param['video_id'];
		$groupId = $param['group_id'];
		$raceId = $param['id'];

		$raceGrp = D('Common/RaceGroup', 'Service')->find(intval($groupId));
		if ($raceGrp['video_ids'] && in_array($videoId, $raceGrp['video_ids'])) {
			$this->error('该视频已推荐');
		}
		if (count($raceGrp['video_ids']) >= 3) {
			$this->error('比赛的推荐视频不能超过3个');
		}
		$raceIds = $raceGrp['race_ids'] ? $raceGrp['race_ids'] : array();
		$videoIds = $raceGrp['video_ids'] ? $raceGrp['video_ids'] : array();
		array_push($raceIds, $raceId);
		array_push($videoIds, $videoId);
		$update = array(
			'race_ids' => $raceIds,
			'video_ids' => $videoIds,
		);

		$flg = D('Common/RaceGroup', 'Service')->where(array('id' => $groupId))->save($update);
		if ($flg === false) {
			$this->error('操作失败，请联系管理员');
		} else {
			$this->success('推荐成功');
		}

	}

	/**
	 * 修改赛事的赛程状态
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */

	public function changeState($id, $state = 0) {
		$map['id'] = intval($id);
		$this->model->where($map)->setField('match_state', intval($state));
		$this->success('更改赛程状态成功');
	}

	/**
	 *删除比赛的前置操作
	 *比赛视频被推荐的，则不能删除
	 *@author susy.liang<liangling@ilongyuan.com.cn>
	 */
	public function _before_del() {
		$ids = array_unique((array) I('id', 0));
		$ids = array_map('intval', $ids);

		$race = $this->model->find($ids[0]);
		if ($race['status'] == 1){
			$this->error('比赛信息已经开启, 不能删除');
		}
		if (empty($race)) {
			$this->error('比赛信息有误');
		}

		$raceGrp = D('Common/RaceGroup', 'Service')->find(intval($race['group_id']));

		if ($raceGrp['race_ids'] && $raceGrp['video_ids']) {
			$raceIds = array_unique($raceGrp['race_ids']);
			foreach ($raceIds as $key => $value) {
				if (in_array($value, $ids)) {
					$this->error('比赛的视频已被推荐，请先取消推荐');
				}
			}
		}
	}

	/**
	 * 推送比赛
	 * @author liubo <liubo@ilongyuan.com.cn>
	 */
	public function push($id)
	{
		$id = intval($id);
		if(IS_POST){
			$content = I('content');
			$data = A('Api/Video', 'Event')->info($id);

			$pEvent = event('Push');

			$pEvent->match($id, $content, $data['game_id']);

			$this->success('操作成功');
		}else{
			$data = A('Api/Video', 'Event')->info($id);
			empty($data) && $this->error('非法操作项');
			$this->assign($data);

			$this->display('push');
		}
	}

}
